from Import.TradeInfoFromCSPDF import *
from Import.TradeInfoFromML import *
from Import.TradeInfoFromBOCI import *
import os
import shutil 
import win32com.client

from Config.ImportConfig import *

def extract_trade_for_ChinaOpps(dir_path = CS_CONF_READ_DIR_PATH):
	
	if not os.path.isdir(dir_path):
		raise RuntimeError(), "Failed to open the dir " + dir_path
	
	#Output to excel
	xApp = win32com.client.Dispatch("Excel.Application")
	xBook = xApp.Workbooks.Open(XLS_TRADE_RECORD_PATH)
	xSht = xBook.Worksheets('Trade Check')
	row = xSht.Range("I65536").End(win32com.client.constants.xlUp).Row + 1
	
	for elem in os.listdir(dir_path):
		file_prefix = os.path.splitext(elem)[0]
		file_suffix = os.path.splitext(elem)[1]
		abs_path = os.path.join(dir_path, elem)
		
		trade_rcd = None
		
		if file_prefix[:17].lower() == 'primenotesconfirm' and  file_suffix[1:].lower() == 'pdf':
			
			trade_rcd = extract_trade_from_CS_PNOTE(abs_path)
	
		elif file_prefix[:12].lower() == 'emb_cman_nja' and  file_suffix[1:].lower() == 'pdf':
		
			trade_rcd = extract_trade_from_CS_HShares(abs_path)
			
		elif file_prefix[:13].lower() == 'hkz_springsca' and  file_suffix[1:].lower() == 'xls':
		
			trade_rcd = extract_trade_from_ML(abs_path)
			
		elif file_prefix[:19].lower() == 'springs-trade recap' and  file_suffix[1:].lower() == 'xls':
		
			trade_rcd = extract_trade_from_BOCI(abs_path)
			
		else:
			print 'Warning: File is not ChinaOpps confirmation ' + elem
			continue
			
		if trade_rcd:
			for elem in trade_rcd:
				xSht.Range(xSht.Cells(row, 9), xSht.Cells(row, 25)).Value = elem
				row += 1
		
		shutil.copy2(abs_path, CS_CONF_BACKUP_DIR_PATH)
		os.remove(abs_path)
			
	xBook.Save()
	xBook.Close()
	del xApp

if __name__ == '__main__':

	extract_trade_for_ChinaOpps()